package com.cn.zengzeng.spbzengzeng.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Description:
 * @Author: zhangzengzeng
 * @Date: 2021/6/23 15:57
 */
@Slf4j
@RestController
@RequestMapping("/redisson")
public class RedissonController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient ;
    @Resource
    private Jedis jedis;
    @Resource
    private RedisTemplate<String, Object> redisTemplate ;
    @GetMapping(value = "stock")
    public String locked(){
        RLock lock = redissonClient.getLock("lock");
        redissonClient.getConfig().setLockWatchdogTimeout(10000);
        int stock = 0;
        try {
            lock.lock();
            //Thread.sleep(200);
            stock = Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get("stock")));
            if(stock<0){
                return "卖完了!";
            }
            System.out.println("当前余量 = " + stock);
            stringRedisTemplate.opsForValue().set("stock",String.valueOf(stock-1));
        }catch(Exception e) {

            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return "当前余量:"+stock ;
    }
    @RequestMapping(value = "handleredis",method = RequestMethod.GET)
    public String handleredis(){
        jedis.set("name","zengzeng");
        return "添加完成";
    }
}
